package repository

import (
	"context"
	"gorm.io/gorm"
	"mts/user_srv/internal/domain"
)

// UserRepository 定义 UserRepository 接口
type UserRepository interface {
	GetUserList(ctx context.Context, req *domain.PageInfo) ([]domain.User, int64, error)
	GetUserByMobile(ctx context.Context, mobile string) (*domain.User, error)
	GetUserById(ctx context.Context, id int32) (*domain.User, error)
	CreateUser(ctx context.Context, user *domain.User) error
	UpdateUser(ctx context.Context, user *domain.User, updates map[string]interface{}) error
	DeleteUser(ctx context.Context, id int32) error
	Count(ctx context.Context) (int, error)
}

// userRepository 实现 UserRepository 接口
type userRepository struct {
	db *gorm.DB
}

func (r *userRepository) Count(ctx context.Context) (int, error) {
	var count int64
	err := r.db.WithContext(ctx).Model(&domain.User{}).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return int(count), nil
}

// NewUserRepository 返回 UserRepository 接口的实现
func NewUserRepository(db *gorm.DB) UserRepository {
	return &userRepository{db: db}
}

// GetUserList 方法实现
func (r *userRepository) GetUserList(ctx context.Context, req *domain.PageInfo) ([]domain.User, int64, error) {
	var users []domain.User
	var total int64
	if err := r.db.WithContext(ctx).Offset(int(req.Pn * req.PSize)).Limit(int(req.PSize)).Find(&users).Error; err != nil {
		return nil, 0, err
	}
	if err := r.db.WithContext(ctx).Model(&domain.User{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}
	return users, total, nil
}

// GetUserByMobile 方法实现
func (r *userRepository) GetUserByMobile(ctx context.Context, mobile string) (*domain.User, error) {
	var user domain.User
	if err := r.db.WithContext(ctx).Where("mobile = ?", mobile).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

// GetUserById 方法实现
func (r *userRepository) GetUserById(ctx context.Context, id int32) (*domain.User, error) {
	var user domain.User
	if err := r.db.WithContext(ctx).Where("id = ?", id).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

// CreateUser 方法实现
func (r *userRepository) CreateUser(ctx context.Context, user *domain.User) error {
	return r.db.WithContext(ctx).Create(user).Error
}

// UpdateUser 方法实现
func (r *userRepository) UpdateUser(ctx context.Context, user *domain.User, updates map[string]interface{}) error {
	return r.db.WithContext(ctx).Model(user).Updates(updates).Error
}

// DeleteUser 方法实现
func (r *userRepository) DeleteUser(ctx context.Context, id int32) error {
	return r.db.WithContext(ctx).Model(&domain.User{}).Where("id = ?", id).Delete(&domain.User{}).Error
}
